# _______________________________________________________________
## _functions.R ----
# _______________________________________________________________

# creating a new environment:
.f <- new.env()

# _______________________________________________________________
## indicator function ----
# _______________________________________________________________

# .f$i <- function(x, cond = TRUE, not = FALSE){
#   na_vals <- which(is.na(x))
#   
#   if(not){
#     out <- as.integer(!(x %in% cond))
#   } else {
#     out <- as.integer(x %in% cond)
#   }
#   
#   out[na_vals] <- NA_integer_
#   return(out)
# }

# _______________________________________________________________
## functions for formatting tables----
# _______________________________________________________________


.f$Kable <- function(x, ...) {
  knitr::kable(x, 
               format = "latex",
               booktabs = TRUE,
               longtable = FALSE,
               linesep = "",
               escape = FALSE,
               ...)
}

.f$KableSave <- function(tex, fname = "") {
  tex <- tex %>% str_split("\n") %>% .[[1]]
  tex <- str_replace_all(tex, "tabular", "tabularx")
  tex <- str_replace_all(tex, "tabularx\\}\\{l", "tabularx}{\\\\textwidth}{X")
  tex <- str_replace_all(tex, "tabularx\\}\\[t\\]\\{l", "tabularx}{\\\\textwidth}{X")
  tex <- str_replace_all(tex, "tab:", str_c("tab:", fname))
  if(fname == "") {
    cat(tex, sep = "\n")
  } else {
    cat(tex, sep = "\n", file = str_c("tables/", fname, ".tex"))
  }
  
}

# _______________________________________________________________
## function for map theme ----
# _______________________________________________________________

.f$theme_map <- function(...) {
  theme_minimal() +
    theme(
      text = element_text(color = "black"),
      axis.line = element_blank(),
      axis.text.x = element_blank(),
      axis.text.y = element_blank(),
      axis.ticks = element_blank(),
      axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      panel.grid.major = element_line(color = "white", size = 0.2),
      panel.grid.minor = element_blank(),
      plot.background = element_rect(fill = "white", color = NA), 
      panel.background = element_rect(fill = "white", color = NA), 
      legend.background = element_rect(fill = "white", color = NA),
      panel.border = element_blank()
    )
}

# _______________________________________________________________
## function for CIs for descriptives  ----
# _______________________________________________________________

.f$summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                         conf.interval=.95, .drop=TRUE) {
  library(plyr)
  
  # New version of length which can handle NA's: if na.rm==T, don't count them
  length2 <- function (x, na.rm=FALSE) {
    if (na.rm) sum(!is.na(x))
    else       length(x)
  }
  
  # This does the summary. For each group's data frame, return a vector with
  # N, mean, and sd
  datac <- ddply(data, groupvars, .drop=.drop,
                 .fun = function(xx, col) {
                   c(N    = length2(xx[[col]], na.rm=na.rm),
                     mean = mean   (xx[[col]], na.rm=na.rm),
                     sd   = sd     (xx[[col]], na.rm=na.rm)
                   )
                 },
                 measurevar
  )
  
  # Rename the "mean" column    
  datac <- rename(datac, c("mean" = "value"))
  
  datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean
  
  # Confidence interval multiplier for standard error
  # Calculate t-statistic for confidence interval: 
  # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
  ciMult <- qt(conf.interval/2 + .5, datac$N-1)
  datac$ci <- datac$se * ciMult
  
  return(datac)
}

# attaching environment:
attach(.f, warn.conflicts = FALSE)
